var mysql = require('mysql-libmysqlclient');
var opt = {
    host : '192.168.0.120',
    database : 'chat',
    user : 'root',
    password : '123123'
};

var conn = null;

connect();


function connect () {
    if(typeof(conn) == null){
        conn = mysql.createConnectionSync();
        conn.connectSync(opt.host, opt.user, opt.password, opt.database);
        conn.setCharsetSync('utf8');

        if (!conn.connectedSync()) {
                console.log("Connection error " + conn.connectErrno + ": " + conn.connectError);
                process.exit(1);
        }
    }
}
exports.join = function(uid, nick){
    conn.query("select uid, nick from ol_users where uid = '"+uid+"'", function(err, res){
        if (err) {
            console.log(err);
            return false;
        }
        res.fetchAll(function (err, rows) {
            if (err) {
                console.log(err);
                return false;
            }
            if(rows[0].uid){
                conn.query("update ol_users set ltime = "+(new Date()).getTime());
            }else{
                conn.query("insert ol_users value('"+uid+"', '"+nick+"', '"+(new Date()).getTime()+"')");
            }
        });
    });
}
exports.addMsg = function(from_uid, to_uid, msg){
    msg = msg.replace("'", "\'");
    conn.query("insert into messages value(null, '"+from_uid+"', '"+to_uid+"', '"+msg+"', '"+(new Date()).getTime()+"')");
}
exports.getMsg = function(){

}